/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.helper;

import cn.emay.sdk.client.api.Client;
import com.minierp.bean.OutBillItemBean;
import com.minierp.bean.QueryParameterCarrier;
import com.minierp.bean.TreeObjectInterface;
import com.minierp.bean.UserBean;
import com.minierp.bean.UserStatus;
import com.minierp.dao.BankAccountBalanceDao;
import com.minierp.dao.BankAccountDetailDao;
import com.minierp.dao.BaseDao;
import com.minierp.dao.BusinessBillDao;
import com.minierp.dao.DbBackupDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.OutBillItemDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.dao.StafferDao;
import com.minierp.dao.StockBalanceDao;
import com.minierp.dao.StockDao;
import com.minierp.dao.TallySetDao;
import com.minierp.dao.UserDao;
import com.minierp.dao.UserPoDao;
import com.minierp.dao.UserPrivilegeDao;
import com.minierp.dao.WorkCenterDao;
import com.minierp.err.StockNoEnoughException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.EncLoginFormCtrHelper;
import com.minierp.listener.OnlineListener;
import com.minierp.model.BankAccount;
import com.minierp.model.BankAccountBalance;
import com.minierp.model.BankAccountDetail;
import com.minierp.model.BusinessBill;
import com.minierp.model.BusinessBillItem;
import com.minierp.model.BusinessProfit;
import com.minierp.model.CodeRule;
import com.minierp.model.DbBackup;
import com.minierp.model.Department;
import com.minierp.model.EnterpriseInfo;
import com.minierp.model.Establishment;
import com.minierp.model.InOutHistory;
import com.minierp.model.Message;
import com.minierp.model.MessageReceiver;
import com.minierp.model.OutBill;
import com.minierp.model.OutBillItem;
import com.minierp.model.Product;
import com.minierp.model.SmsTask;
import com.minierp.model.Staffer;
import com.minierp.model.Stock;
import com.minierp.model.StockBalance;
import com.minierp.model.Storehouse;
import com.minierp.model.SystemLog;
import com.minierp.model.TallySet;
import com.minierp.model.User;
import com.minierp.model.WorkCenter;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import mobset.smsSDK;
import mobset.str_SendMsg;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.hibernate.Query;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.PrototypicalNodeFactory;
import org.htmlparser.Remark;
import org.htmlparser.Tag;
import org.htmlparser.Text;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.SimpleNodeIterator;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class PageHelper {
	private static Client emayClient = null;
	private static smsSDK mobsetClient = null;

	public static String getSmsCode() {
		String smsCode = EncCommonHelper.getProperty("smsCode");
		String smsClientType = EncCommonHelper.getProperty("smsClientType");
		return smsClientType != null && !smsClientType.equals("")
				&& smsCode != null ? (smsClientType.equals("EMAY")
				&& smsCode.indexOf("-GYK-") == -1 ? "" : smsCode) : "";
	}

	private static synchronized void getSmsClient() {
		String smsClientType = EncCommonHelper.getProperty("smsClientType");
		if (smsClientType != null) {
			if (smsClientType.equals("EMAY")) {
				if (emayClient == null) {
					try {
						String e = getSmsCode();
						if (e != null && !e.equals("")) {
							emayClient = new Client(e,
									EncCommonHelper.getProperty("smsKey"));
						}
					} catch (Exception arg1) {
						System.out
								.println("**************get sms client error:"
										+ arg1);
					}
				}

				EncCommonHelper.debug("************get emay sms client:"
						+ emayClient);
			} else if (smsClientType.equals("MOBSET")) {
				if (mobsetClient == null) {
					mobsetClient = new smsSDK();
					mobsetClient.Sms_Connect("www.mobset.com", 12345, "用户名",
							"密码", 30);
				}

				EncCommonHelper.debug("************get mobset sms client:"
						+ mobsetClient);
			}
		}

	}

	public static int smsSend(String receiverCode, String content, Date planTime) {
		int s = -1;
		getSmsClient();
		String smsClientType = EncCommonHelper.getProperty("smsClientType");
		if (smsClientType != null) {
			if (smsClientType.equals("EMAY")) {
				if (emayClient != null) {
					if (planTime != null) {
						SimpleDateFormat sendMsg = new SimpleDateFormat(
								"yyyyMMddHHmmss");
						s = emayClient.sendScheduledSMS(
								new String[]{receiverCode}, content,
								sendMsg.format(planTime));
					} else {
						s = emayClient.sendSMS(new String[]{receiverCode},
								content, 3);
					}
				}
			} else if (smsClientType.equals("MOBSET") && mobsetClient != null) {
				str_SendMsg[] sendMsg1 = new str_SendMsg[1];
				sendMsg1[0].dTimer = planTime;
				sendMsg1[0].strMobile = receiverCode;
				sendMsg1[0].strMsg = content;
				s = mobsetClient.Sms_Send(sendMsg1, 1);
			}
		}

		return s;
	}

	public static double getSmsBalance() {
		double balance = 0.0D;
		getSmsClient();
		String smsClientType = EncCommonHelper.getProperty("smsClientType");
		if (smsClientType != null) {
			if (smsClientType.equals("EMAY")) {
				if (emayClient != null) {
					try {
						balance = emayClient.getBalance();
					} catch (Exception arg3) {
						arg3.printStackTrace();
						balance = -1.0D;
					}
				}
			} else if (smsClientType.equals("MOBSET")) {
				balance = (double) mobsetClient.Sms_KYSms();
			}
		}

		return balance;
	}

	public static void clearSmsClient() {
		String smsClientType = EncCommonHelper.getProperty("smsClientType");
		if (smsClientType != null && smsClientType.equals("EMAY")) {
			if (emayClient != null) {
				emayClient.closeChannel();
			} else {
				smsClientType.equals("MOBSET");
			}
		}

	}

	public static String generateCode(SerialNumberDao snDao, CodeRule cr,
			String typeCode, long tallySetId) throws Exception {
		String code = "";
		String separator = "";
		if (cr.getSeparator() != null) {
			separator = cr.getSeparator();
		}

		String prefixStr = cr.getPrefix();
		if (cr.getDataType() == 3
				&& cr.getTallySetRule().equals("INDEPENDENCE")) {
			prefixStr = prefixStr + "(" + tallySetId + ")";
		}

		Date now = new Date();
		SimpleDateFormat sf = null;
		if (cr.getGenerateRule().equals("AUTO_DATE")) {
			sf = new SimpleDateFormat("yyyyMMdd");
			prefixStr = prefixStr + separator + sf.format(now);
		} else if (cr.getGenerateRule().equals("AUTO_MONTH")) {
			sf = new SimpleDateFormat("yyyyMM");
			prefixStr = prefixStr + separator + sf.format(now);
		} else if (cr.getGenerateRule().equals("AUTO_YEAR")) {
			sf = new SimpleDateFormat("yyyy");
			prefixStr = prefixStr + separator + sf.format(now);
		} else if (!cr.getGenerateRule().equals("AUTO_PREFIX")
				&& cr.getGenerateRule().equals("AUTO_TYPE_CODE")) {
			prefixStr = typeCode;
		}

		if (!prefixStr.equals("")) {
			int currentNum = snDao.getCurrentNum(cr.getId(), prefixStr);
			code = prefixStr
					+ separator
					+ EncCommonHelper.zeroPadString(String.valueOf(currentNum),
							cr.getNumberLength());
		}

		if (code != null && !code.equals("")) {
			return code;
		} else {
			throw new Exception("生成编号错误：无法生成编号！");
		}
	}

	public static void setQueryValue(Query q, QueryParameterCarrier[] objs)
			throws Exception {
		for (int i = 0; i < objs.length; ++i) {
			if (objs[i].propertyName != null
					&& !objs[i].propertyName.equals("")) {
				switch (objs[i].dataType) {
					case 1 :
						String tmp = objs[i].value.trim();
						if (!tmp.equals("")) {
							if (objs[i].logicType == 9) {
								tmp = "%" + tmp + "%";
							} else if (objs[i].logicType == 7) {
								tmp = tmp + "%";
							} else if (objs[i].logicType == 8) {
								tmp = "%" + tmp;
							}

							q.setString(objs[i].propertyName + i, tmp);
						}
						break;
					case 2 :
						q.setInteger(objs[i].propertyName + i,
								Integer.parseInt(objs[i].value));
						break;
					case 3 :
						q.setLong(objs[i].propertyName + i,
								Long.parseLong(objs[i].value));
						break;
					case 4 :
						SimpleDateFormat sd = new SimpleDateFormat(
								objs[i].dateFormatStr);
						q.setDate(objs[i].propertyName + i,
								sd.parse(objs[i].value));
						break;
					case 5 :
						q.setBigDecimal(objs[i].propertyName + i,
								new BigDecimal(objs[i].value));
					case 6 :
						break;
					case 7 :
						q.setBoolean(objs[i].propertyName + i, (new Boolean(
								objs[i].value)).booleanValue());
						break;
					default :
						q.setString(objs[i].propertyName + i, objs[i].value);
				}
			}
		}

	}

	public static Connection getConnection(ServletContext sc) {
		WebApplicationContext ctx = WebApplicationContextUtils
				.getWebApplicationContext(sc);
		return DataSourceUtils.getConnection((DataSource) ctx
				.getBean("dataSource"));
	}

	public static BigDecimal setCostInfo(HttpServletRequest request,
			List outBillItemBeanList, StockDao stockDao, long storehouseId) {
		BigDecimal totalCost = new BigDecimal(0);
		if (EncCommonHelper.checkPrivilege(request, "STOR_COST")) {
			for (int i = 0; i < outBillItemBeanList.size(); ++i) {
				OutBillItemBean cb = (OutBillItemBean) outBillItemBeanList
						.get(i);
				OutBillItem c = cb.getOutBillItem();
				if (!cb.getStatus().equals("DELETE") && c.getProductId() != 0L) {
					Stock st = stockDao.get(c.getProductId(), storehouseId);
					if (st == null) {
						cb.setStockAmount(new BigDecimal(0));
						cb.setUnitPrice(new BigDecimal(0));
					} else {
						BigDecimal unitPrice = st.getUnitPrice();
						BigDecimal cost = unitPrice.multiply(c.getAmount())
								.setScale(2, 4);
						cb.setStockAmount(st.getAmount());
						cb.setUnitPrice(unitPrice);
						c.setCost(cost);
						totalCost = totalCost.add(cost);
					}
				}
			}
		}

		return totalCost;
	}

	public static BigDecimal setCostInfo(List outBillItemBeanList) {
		BigDecimal totalCost = new BigDecimal(0);

		for (int i = 0; i < outBillItemBeanList.size(); ++i) {
			OutBillItemBean cb = (OutBillItemBean) outBillItemBeanList.get(i);
			OutBillItem c = cb.getOutBillItem();
			cb.setUnitPrice(c.getUnitPrice());
			totalCost = totalCost.add(c.getCost());
		}

		return totalCost;
	}

	public static void updateBankAccount(long bankAccountId, long tallySetId,
			long billId, BigDecimal cost, Date billDate, Date costDate,
			String billCode, String billType, String extBillType,
			String costType, String rcType, String managerName, String mark,
			String financeType, String operType, boolean updaLogData,
			BankAccountDetailDao bankAccountDetailDao,
			BankAccountBalanceDao bankAccountBalanceDao, IdGenerator idGenerator)
			throws Exception {
		if (cost.compareTo(new BigDecimal(0)) != 0) {
			BankAccount ba = (BankAccount) bankAccountBalanceDao.get(
					BankAccount.class, bankAccountId);
			if (ba == null) {
				throw new Exception("Bank account not found for id:"
						+ bankAccountId);
			}

			if (rcType.equals("R")) {
				ba.setCurrentCost(ba.getCurrentCost().add(cost));
			} else {
				ba.setCurrentCost(ba.getCurrentCost().subtract(cost));
			}

			bankAccountBalanceDao.update(ba);
			if (updaLogData) {
				bankAccountDetailDao.updateLogData(billType, billId);
			}

			BankAccountDetail bad = new BankAccountDetail();
			bad.setBankAccountId(bankAccountId);
			bad.setBillCode(billCode);
			bad.setBillId(billId);
			bad.setBillType(billType);
			bad.setBillDate(billDate);
			bad.setExtBillType(extBillType);
			bad.setCost(cost);
			bad.setBaCost(ba.getCurrentCost());
			bad.setCostDate(costDate);
			bad.setCostType(costType);
			bad.setId(idGenerator.getId(BankAccountDetail.class.getName()));
			bad.setManagerName(managerName);
			if (mark != null && mark.length() > 300) {
				mark = mark.substring(0, 297) + "...";
			}

			bad.setMark(mark);
			bad.setRcType(rcType);
			bad.setTallySetId(tallySetId);
			bad.setFinanceType(financeType);
			bad.setOperType(operType);
			if (!operType.equals("UN_EXAM") && !operType.equals("CANC")) {
				bad.setLogData("N");
			} else {
				bad.setLogData("Y");
			}

			bankAccountBalanceDao.save(bad);
			SimpleDateFormat sfMonth = new SimpleDateFormat("yyyy-MM");
			String startDateStr = sfMonth.format(billDate) + "-01";
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			c.setTime(sf.parse(startDateStr));
			c.add(2, 1);
			Date balanceDate = c.getTime();
			BankAccountBalance preBalance = bankAccountBalanceDao
					.getPreviousBalance(bankAccountId, billDate);
			BigDecimal preCost = new BigDecimal(0);
			if (preBalance != null) {
				preCost = preBalance.getCost();
			}

			List list = bankAccountBalanceDao.getList(bankAccountId, billDate);
			BankAccountBalance firBalance;
			if (list.isEmpty()) {
				firBalance = new BankAccountBalance();
				firBalance.setBalanceDate(balanceDate);
				firBalance.setBankAccountId(bankAccountId);
				if (rcType.equals("R")) {
					firBalance.setCost(preCost.add(cost));
				} else {
					firBalance.setCost(preCost.subtract(cost));
				}

				firBalance.setId(idGenerator.getId(BankAccountBalance.class
						.getName()));
				bankAccountBalanceDao.save(firBalance);
			} else {
				for (int arg35 = 0; arg35 < list.size(); ++arg35) {
					BankAccountBalance bdStr = (BankAccountBalance) list
							.get(arg35);
					if (rcType.equals("R")) {
						bdStr.setCost(bdStr.getCost().add(cost));
					} else {
						bdStr.setCost(bdStr.getCost().subtract(cost));
					}

					bankAccountBalanceDao.update(bdStr);
				}

				firBalance = (BankAccountBalance) list.get(0);
				String arg36 = sf.format(balanceDate);

				for (String firBdStr = sf.format(firBalance.getBalanceDate()); !arg36
						.equals(firBdStr); arg36 = sf.format(balanceDate)) {
					BankAccountBalance b = new BankAccountBalance();
					b.setBalanceDate(balanceDate);
					b.setBankAccountId(bankAccountId);
					if (rcType.equals("R")) {
						b.setCost(preCost.add(cost));
					} else {
						b.setCost(preCost.subtract(cost));
					}

					b.setId(idGenerator.getId(BankAccountBalance.class
							.getName()));
					bankAccountBalanceDao.save(b);
					c.setTime(balanceDate);
					c.add(2, 1);
					balanceDate = c.getTime();
				}
			}
		}

	}

	public static String getRequName(long requId, String requType,
			BaseDao baseDao) {
		String requName = "";
		if (requType != null && requId != 0L) {
			if (!requType.equals("CLIENT") && !requType.equals("PROVIDER")
					&& !requType.equals("COOPERATOR")) {
				if (requType.equals("DEPARTMENT")) {
					Department wc1 = (Department) baseDao.get(Department.class,
							requId);
					if (wc1 != null) {
						requName = wc1.getDepartmentName();
					}
				} else if (requType.equals("STOREHOUSE")) {
					Storehouse wc2 = (Storehouse) baseDao.get(Storehouse.class,
							requId);
					if (wc2 != null) {
						requName = wc2.getStoName();
					}
				} else if (requType.equals("WORK_CENTER")) {
					WorkCenter wc3 = (WorkCenter) baseDao.get(WorkCenter.class,
							requId);
					if (wc3 != null) {
						requName = wc3.getWcName();
					}
				}
			} else {
				Establishment wc = (Establishment) baseDao.get(
						Establishment.class, requId);
				if (wc != null) {
					requName = wc.getEstName();
				}
			}
		}

		return requName;
	}

	public static String stockNotEnoughMeg(BaseDao baseDao, long productId,
			BigDecimal stockAmount, BigDecimal difAmount) {
		Product p = (Product) baseDao.get(Product.class, productId);
		String msg = "";
		if (p == null) {
			msg = "id为『" + productId + "』的产品库存不足";
		} else {
			msg = "『" + p.getProductName() + "』库存不足";
		}

		msg = msg + "，当前库存量为" + stockAmount + "，差额为" + difAmount;
		return msg;
	}

	public static BigDecimal updateOutBillStock(OutBill b, List items,
			StockDao stockDao, StockBalanceDao stockBalanceDao,
			IdGenerator idGenerator, String requName, String operType,
			String stafName, String iohMark) throws StockNoEnoughException,
			ParseException {
		String stoOper = "";
		if (!operType.equals("SAVE_EXAM") && !operType.equals("EXAM")) {
			stoOper = "ADD";
		} else {
			stoOper = "SUB";
		}

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		BigDecimal zero = new BigDecimal(0);
		BigDecimal outCost = new BigDecimal(0);

		for (int j = 0; j < items.size(); ++j) {
			OutBillItem it = (OutBillItem) items.get(j);
			Stock s = stockDao.get(it.getProductId(), b.getStorehouseId());
			new BigDecimal(0);
			new BigDecimal(0);
			String arg20;
			if (s == null) {
				if (stoOper.equals("ADD")) {
					throw new StockNoEnoughException("没有id为"
							+ it.getProductId() + "产品在仓库" + b.getStorehouseId()
							+ "的记录！");
				}

				arg20 = stockNotEnoughMeg(stockDao, it.getProductId(),
						new BigDecimal(0), it.getAmount());
				throw new StockNoEnoughException(arg20);
			}

			BigDecimal currentAmount = s.getAmount();
			BigDecimal iohCost;
			BigDecimal iohUp;
			if (stoOper.equals("ADD")) {
				iohCost = it.getCost();
				iohUp = it.getUnitPrice();
				s.setAmount(s.getAmount().add(it.getAmount()));
				s.setCost(s.getCost().add(iohCost));
				if (s.getAmount().compareTo(new BigDecimal(0)) != 0) {
					s.setUnitPrice(s.getCost().divide(s.getAmount(), 4, 4));
				}

				stockDao.update(s);
			} else {
				iohCost = it.getAmount().multiply(s.getUnitPrice())
						.setScale(2, 4);
				iohUp = s.getUnitPrice().setScale(4, 4);
				it.setCost(iohCost);
				it.setUnitPrice(iohUp);
				stockDao.update(it);
				s.setAmount(s.getAmount().subtract(it.getAmount()));
				s.setCost(s.getCost().subtract(iohCost));
				if (s.getAmount().compareTo(new BigDecimal(0)) != 0) {
					s.setUnitPrice(s.getCost().divide(s.getAmount(), 4, 4));
				}

				stockDao.update(s);
			}

			if (s.getAmount().compareTo(new BigDecimal(0)) == -1) {
				arg20 = stockNotEnoughMeg(stockDao, it.getProductId(),
						currentAmount, s.getAmount());
				throw new StockNoEnoughException(arg20);
			}

			updateStockBalance(stockBalanceDao, it.getProductId(),
					it.getAmount(), b.getOutDate(), iohCost,
					b.getStorehouseId(), idGenerator, stoOper);
			if (operType.equals("UN_EXAM") || operType.equals("CANC")) {
				stockDao.updateIohLogData("OUT_BILL", b.getId());
			}

			InOutHistory h = new InOutHistory();
			h.setBillId(b.getId());
			h.setBillCode(b.getBillCode());
			h.setBillDate(b.getOutDate());
			h.setProId(it.getProductId());
			h.setStoId(b.getStorehouseId());
			h.setBillType("OUT_BILL");
			h.setId(idGenerator.getId(InOutHistory.class.getName()));
			h.setOperType(operType);
			h.setIoType("OUT");
			h.setTypeId(b.getOutTypeId());
			h.setRequType(b.getRequirerType());
			h.setRequId(b.getRequirerId());
			h.setRequName(requName);
			h.setBbCode(b.getBusinessBillCode());
			h.setUnitPrice(iohUp);
			h.setStorAmou(s.getAmount());
			h.setStorCost(s.getCost());
			h.setStorUp(s.getUnitPrice());
			String mark;
			if (operType.equals("UN_EXAM")) {
				h.setLogData("Y");
				h.setCost(zero.subtract(iohCost));
				h.setAmount(zero.subtract(it.getAmount()));
				mark = stafName + "于" + sf.format(h.getIoTime()) + "反审核单据";
			} else if (operType.equals("CANC")) {
				h.setLogData("Y");
				h.setCost(zero.subtract(iohCost));
				h.setAmount(zero.subtract(it.getAmount()));
				mark = stafName + "于" + sf.format(h.getIoTime()) + "作废单据";
			} else {
				h.setLogData("N");
				h.setCost(iohCost);
				h.setAmount(it.getAmount());
				mark = it.getMark();
			}

			if (iohMark != null && !iohMark.equals("")) {
				h.setMark(iohMark);
			} else {
				h.setMark(mark);
			}

			stockDao.save(h);
			outCost = outCost.add(iohCost);
		}

		return outCost;
	}

	public static void cancelOutBill(OutBill b, UserBean ub, String reason,
			BusinessBill bb, BigDecimal bbAdju, String cancType,
			OutBillItemDao outBillItemDao, BusinessBillDao businessBillDao,
			StockDao stockDao, StockBalanceDao stockBalanceDao,
			IdGenerator idGenerator) throws Exception {
		if (b != null && b.getEnabled().equals("Y")) {
			b.setEnabled("N");
			b.setDisableManId(ub.getUser().getStafferId());
			b.setUpdateTime(new Date());
			outBillItemDao.update(b);
			BigDecimal outCost = new BigDecimal(0);
			if (b.getExamined().equals("Y")) {
				String log = getRequName(b.getRequirerId(),
						b.getRequirerType(), outBillItemDao);
				List itemList = outBillItemDao.getList(b.getId());
				String iohMark = null;
				if (cancType.equals("BUSI_UNCOMP")) {
					iohMark = "业务单反完工，自动作废相应的出库单";
				}

				outCost = updateOutBillStock(b, itemList, stockDao,
						stockBalanceDao, idGenerator, log, "CANC", ub
								.getStaffer().getStafferName(), iohMark);
			}

			if (b.getExamined().equals("Y") && bb != null) {
				BusinessProfit log1 = businessBillDao.getBusinessProfit(bb
						.getBillCode());
				if (log1 == null) {
					log1 = new BusinessProfit();
					log1.setBbCode(bb.getBillCode());
					log1.setId(idGenerator.getId(BusinessProfit.class.getName()));
					log1.setCooperCost(new BigDecimal(0));
					log1.setFeeCost(new BigDecimal(0));
					log1.setMaterialCost((new BigDecimal(0)).subtract(outCost));
					log1.setProfitCost(bb.getCost().add(bbAdju)
							.subtract(log1.getMaterialCost()));
					businessBillDao.save(log1);
				} else {
					log1.setMaterialCost(log1.getMaterialCost().subtract(
							outCost));
					log1.setProfitCost(log1.getProfitCost().add(outCost));
					businessBillDao.update(log1);
				}
			}

			SystemLog log2 = new SystemLog();
			log2.setId(idGenerator.getId(SystemLog.class.getName()));
			log2.setActionCode("OUT_BILL");
			log2.setLogType("CANCEL_LOG");
			log2.setCreaterId(ub.getStaffer().getId());
			log2.setCreaterName(ub.getStaffer().getStafferName());
			log2.setDepName(ub.getDepName());
			log2.setDepId(ub.getStaffer().getDepartmentId());
			log2.setStatus("S");
			log2.setUserName(ub.getUser().getUserName());
			log2.setIp(b.getBillCode());
			log2.setMark("");
			log2.setRelId(b.getId());
			log2.setCancelReason(reason);
			log2.setTallySetId(b.getTallySetId());
			outBillItemDao.save(log2);
		}

	}

	public static void updateStockBalance(StockBalanceDao stockBalanceDao,
			long productId, BigDecimal amount, Date startDate, BigDecimal cost,
			long storehouseId, IdGenerator idGenerator, String addOrSub)
			throws ParseException {
		SimpleDateFormat sfMonth = new SimpleDateFormat("yyyy-MM");
		String startDateStr = sfMonth.format(startDate) + "-01";
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.setTime(sf.parse(startDateStr));
		c.add(2, 1);
		Date balanceDate = c.getTime();
		StockBalance preBalance = stockBalanceDao.getPreviousBalance(productId,
				storehouseId, startDate);
		BigDecimal preAmount;
		BigDecimal preCost;
		if (preBalance == null) {
			preAmount = new BigDecimal(0);
			preCost = new BigDecimal(0);
		} else {
			preAmount = preBalance.getAmount();
			preCost = preBalance.getCost();
		}

		List list = stockBalanceDao.getList(productId, storehouseId, startDate);
		StockBalance firBalance;
		if (list.isEmpty()) {
			firBalance = new StockBalance();
			firBalance.setId(idGenerator.getId(StockBalance.class.getName()));
			if (addOrSub.equals("ADD")) {
				firBalance.setAmount(preAmount.add(amount));
				firBalance.setCost(preCost.add(cost));
			} else {
				firBalance.setAmount(preAmount.subtract(amount));
				firBalance.setCost(preCost.subtract(cost));
			}

			firBalance.setProductId(productId);
			firBalance.setStorehouseId(storehouseId);
			firBalance.setBalanceDate(balanceDate);
			stockBalanceDao.save(firBalance);
		} else {
			for (int arg22 = 0; arg22 < list.size(); ++arg22) {
				StockBalance bdStr = (StockBalance) list.get(arg22);
				if (addOrSub.equals("ADD")) {
					bdStr.setAmount(bdStr.getAmount().add(amount));
					bdStr.setCost(bdStr.getCost().add(cost));
				} else {
					bdStr.setAmount(bdStr.getAmount().subtract(amount));
					bdStr.setCost(bdStr.getCost().subtract(cost));
				}

				stockBalanceDao.update(bdStr);
			}

			firBalance = (StockBalance) list.get(0);
			String arg23 = sf.format(balanceDate);

			for (String firBdStr = sf.format(firBalance.getBalanceDate()); !arg23
					.equals(firBdStr); arg23 = sf.format(balanceDate)) {
				StockBalance s = new StockBalance();
				s.setId(idGenerator.getId(StockBalance.class.getName()));
				if (addOrSub.equals("ADD")) {
					s.setAmount(preAmount.add(amount));
					s.setCost(preCost.add(cost));
				} else {
					s.setAmount(preAmount.subtract(amount));
					s.setCost(preCost.subtract(cost));
				}

				s.setProductId(productId);
				s.setStorehouseId(storehouseId);
				s.setBalanceDate(balanceDate);
				stockBalanceDao.save(s);
				c.setTime(balanceDate);
				c.add(2, 1);
				balanceDate = c.getTime();
			}
		}

	}

	public static List getTallySetList(TallySetDao tallySetDao, UserBean ub) {
		return ub.getUser().getUserType() == 1
				? tallySetDao.getList(true)
				: tallySetDao.getList(ub.getUser().getId());
	}

	public static List getWorkCenterList(WorkCenterDao workCenterDao,
			UserBean ub, EnterpriseInfo ent) {
		return ub.getUser().getUserType() != 1
				&& !ent.getWorkCenter().equals("N") ? workCenterDao.getList(ub
				.getUser().getId()) : workCenterDao.getList(true);
	}

	public static String parseClearHtmlTag(String source, int subLength,
			String moreString, boolean lineFeed) throws Exception {
		StringBuffer str = new StringBuffer();
		HashMap map = new HashMap();
		map.put("currentLength", "0");
		if (source != null && !source.equals("")) {
			PrototypicalNodeFactory currentLength = new PrototypicalNodeFactory();
			Parser s = new Parser();
			s.setNodeFactory(currentLength);
			s.setEncoding("gbk");
			s.setInputHTML(source);
			NodeIterator nit = s.elements();
			boolean breaked = false;

			while (nit.hasMoreNodes()) {
				Node anode = nit.nextNode();
				if (anode instanceof Text) {
					String txt = ((Text) anode).getText();
					if (txt == null
							|| !txt.toLowerCase().startsWith("<?xml:namespace")) {
						breaked = parseClearHtmlTagDealText(str, anode,
								subLength, map);
					}
				} else if (anode instanceof Tag) {
					breaked = parseClearHtmlTagDealTag(str, (Tag) anode,
							subLength, lineFeed, map);
				} else {
					boolean arg9999 = anode instanceof Remark;
				}

				if (breaked) {
					break;
				}
			}
		}

		int currentLength1 = Integer.parseInt(((String) map
				.get("currentLength")).toString());
		if (subLength > 0 && currentLength1 >= subLength) {
			str = str.append(moreString);
		}

		String s1 = str.toString();
		s1 = s1.replace("<", "&lt;");
		s1 = s1.replace(">", "&gt;");
		return s1;
	}

	private static boolean parseClearHtmlTagDealText(StringBuffer str,
			Node anode, int subLength, Map<String, String> map)
			throws Exception {
		boolean breaked = false;
		String txt = anode.getText();
		if (txt != null && !txt.trim().equals("")
				&& !txt.toLowerCase().startsWith("<?xml:namespace")) {
			txt = txt.replace("&nbsp;", " ");
			txt = txt.replace("&gt;", ">");
			txt = txt.replace("&lt;", "<");
			if (subLength > 0) {
				breaked = addToString(str, txt, subLength, map);
			} else {
				str.append(txt);
			}
		}

		return breaked;
	}

	private static boolean parseClearHtmlTagDealTag(StringBuffer str, Tag aTag,
			int subLength, boolean lineFeed, Map<String, String> map)
			throws Exception {
		boolean breaked = false;
		NodeList list = aTag.getChildren();
		boolean hasText = false;
		if (list != null) {
			SimpleNodeIterator it = list.elements();

			while (it.hasMoreNodes()) {
				Node node = it.nextNode();
				if (node instanceof Text) {
					if (node.getText() != null
							&& !node.getText().trim().equals("")) {
						hasText = true;
					}

					breaked = parseClearHtmlTagDealText(str, node, subLength,
							map);
				} else if (node instanceof Tag) {
					breaked = parseClearHtmlTagDealTag(str, (Tag) node,
							subLength, lineFeed, map);
				} else {
					boolean arg9999 = node instanceof Remark;
				}

				if (breaked) {
					break;
				}
			}
		}

		if (!breaked) {
			if (hasText) {
				if (aTag.getTagName().equalsIgnoreCase("P")
						|| aTag.getTagName().equalsIgnoreCase("TD")) {
					str.append(" ");
				}
			} else if (aTag.getTagName().equalsIgnoreCase("BR")) {
				str.append(" ");
			}
		}

		return breaked;
	}

	private static boolean addToString(StringBuffer str, String tmpStr,
			int subLength, Map<String, String> map) throws Exception {
		int currentLength = Integer
				.parseInt(((String) map.get("currentLength")).toString());
		boolean flag = false;

		for (int i = 0; i < tmpStr.length(); ++i) {
			if (currentLength >= subLength) {
				flag = true;
				break;
			}

			String s2 = tmpStr.substring(i, i + 1);
			byte[] abyte0 = s2.getBytes("gbk");
			if (abyte0.length != 2 && !s2.equals("m") && !s2.equals("M")
					&& !s2.equals("W")) {
				++currentLength;
			} else {
				currentLength += 2;
			}

			str.append(s2);
		}

		map.put("currentLength", String.valueOf(currentLength));
		return flag;
	}

	public static String getPingYin(String src) {
      char[] t1 = src.toCharArray();
      String[] t2 = new String[t1.length];
      HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
      t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
      t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
      t3.setVCharType(HanyuPinyinVCharType.WITH_V);
      String t4 = "";
      int t0 = t1.length;

      try {
         for(int e1 = 0; e1 < t0; ++e1) {
            if(Character.toString(t1[e1]).matches("[\一-\龥]+")) {
               t2 = PinyinHelper.toHanyuPinyinStringArray(t1[e1], t3);
               t4 = t4 + t2[0];
            } else {
               t4 = t4 + Character.toString(t1[e1]);
            }
         }

         return t4;
      } catch (BadHanyuPinyinOutputFormatCombination arg6) {
         arg6.printStackTrace();
         return t4;
      }
   }
	public static String getPinYinHeadChar(String str) {
		String convert = "";

		for (int j = 0; j < str.length(); ++j) {
			char word = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert = convert + pinyinArray[0].charAt(0);
			} else {
				convert = convert + word;
			}
		}

		return convert;
	}

	public static String getCnASCII(String cnStr) {
		StringBuffer strBuf = new StringBuffer();
		byte[] bGBK = cnStr.getBytes();

		for (int i = 0; i < bGBK.length; ++i) {
			strBuf.append(Integer.toHexString(bGBK[i] & 255));
		}

		return strBuf.toString();
	}

	public static String getMysqlBinPath(ServletContext ct) {
		String appPath = ct.getRealPath("/");
		if (!appPath.endsWith(File.separator)) {
			appPath = appPath + File.separator;
		}

		return appPath + ".." + File.separator + ".." + File.separator
				+ "mysql" + File.separator + "bin" + File.separator;
	}

	public static String getDbPort(ServletContext ct) {
		String dbPort = EncCommonHelper.getProperty("dbPort");
		if (dbPort == null || dbPort.equals("")) {
			dbPort = "3306";
		}

		return dbPort;
	}

	public static String[] getDbBackupFileName(ServletContext ct,
			EnterpriseInfo ent) {
		String[] arr = new String[]{"", ""};
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String todayStr = sf.format(new Date());
		String thistimePath = todayStr;
		String fileName = EncCommonHelper.getProperty("sysCode") + "."
				+ EncCommonHelper.getProperty("version");
		String basePath = ct.getRealPath("/");
		if (!basePath.endsWith(File.separator)) {
			basePath = basePath + File.separator;
		}

		String backupFolder = basePath + "WEB-INF" + File.separator
				+ "db_backup" + File.separator;
		File file = new File(backupFolder + todayStr);

		int i;
		for (i = 0; file.exists() && file.isDirectory(); file = new File(
				backupFolder + thistimePath)) {
			++i;
			thistimePath = todayStr + "_" + i;
		}

		file.mkdirs();
		arr[0] = backupFolder + thistimePath + File.separator + fileName
				+ ".sql";
		if (ent.getDbBackupFolder() != null
				&& !ent.getDbBackupFolder().equals("")) {
			backupFolder = ent.getDbBackupFolder();
			if (!backupFolder.endsWith(File.separator)) {
				backupFolder = backupFolder + File.separator;
			}

			file = new File(backupFolder + thistimePath);

			for (i = 0; file.exists() && file.isDirectory(); file = new File(
					backupFolder + thistimePath)) {
				++i;
				thistimePath = todayStr + "_" + i;
			}

			file.mkdirs();
			arr[1] = backupFolder + thistimePath + File.separator + fileName
					+ ".sql";
		}

		return arr;
	}

	public static void dbBackup(DbBackupDao dbBackupDao, long recordId,
			String mysqlPath, String dbPort, String copyName) {
		DbBackup b = (DbBackup) dbBackupDao.get(DbBackup.class, recordId);
		if (b != null) {
			String fileName;
			if (copyName != null && !copyName.equals("")) {
				fileName = copyName;
			} else {
				fileName = b.getFileName();
			}

			String command = "cmd /C " + mysqlPath
					+ "mysqldump -uroot -pmyminierp -P" + dbPort + " minierp>"
					+ fileName;
			InputStreamReader ir = null;
			BufferedReader br = null;
			Runtime r = Runtime.getRuntime();
			Process p = null;

			try {
				EncCommonHelper.debug("************db backup:" + command);
				p = r.exec(command);
				ir = new InputStreamReader(p.getInputStream());
				br = new BufferedReader(ir);

				for (String e = br.readLine(); e != null; e = br.readLine()) {
					EncCommonHelper.debug("************db backup:" + e);
				}

				File file = new File(fileName);
				b.setFileSize(file.length());
				if (file.exists() && file.isFile() && file.length() >= 5120L) {
					b.setCompleteFlag("Y");
				} else {
					b.setCompleteFlag("F");
				}

				dbBackupDao.update(b);
				if (copyName != null && !copyName.equals("")) {
					try {
						EncCommonHelper.debug("************db backup:"
								+ b.getFileName());
						FileCopyUtils.copy(file, new File(b.getFileName()));
					} catch (Exception arg32) {
						arg32.printStackTrace();
					}
				}

				EncCommonHelper.debug("************db backup:thread finish!");
			} catch (Exception arg33) {
				arg33.printStackTrace();
			} finally {
				try {
					if (br != null) {
						br.close();
					}
				} catch (Exception arg31) {
					;
				}

				try {
					if (ir != null) {
						ir.close();
					}
				} catch (Exception arg30) {
					;
				}

				try {
					if (p != null && p.getInputStream() != null) {
						p.getInputStream().close();
						p.getOutputStream().close();
						p.getErrorStream().close();
						p.destroy();
						p = null;
					}
				} catch (Exception arg29) {
					;
				}

			}
		}

	}

	public static boolean isMobileCode(String str) {
		if (str != null && str.length() == 11 && str.indexOf(".") == -1
				&& str.indexOf("+") == -1 && str.indexOf("-") == -1) {
			try {
				Long.parseLong(str);
				return true;
			} catch (Exception arg1) {
				return false;
			}
		} else {
			return false;
		}
	}

	public static boolean isEmail(String str) {
		if (str != null && !str.equals("")) {
			int index = str.indexOf("@");
			return index != -1 && index != 0 && index != str.length() - 1;
		} else {
			return false;
		}
	}

	public static String escapeXml(String str) {
		if (str == null) {
			str = "";
		}

		str = str.replace("\'", "&#039;");
		str = str.replace("\"", "&#034;");
		return str;
	}

	public static String createIdArrStr(long[] idArr, String fieldName,
			boolean needAnd) {
		String str = "";
		if (idArr != null && idArr.length > 0) {
			if (idArr.length == 1) {
				str = " " + fieldName + "=" + idArr[0];
			} else {
				String tmpStr = "";

				for (int i = 0; i < idArr.length; ++i) {
					if (!tmpStr.equals("")) {
						tmpStr = tmpStr + ",";
					}

					tmpStr = tmpStr + idArr[i];
				}

				str = " (" + fieldName + " in (" + tmpStr + "))";
			}

			if (needAnd) {
				str = " and " + str;
			}
		}

		return str;
	}

	public static String createIdArrStr(String[] idArr, String fieldName,
			boolean needAnd) {
		long[] arr = new long[idArr.length];

		for (int i = 0; i < idArr.length; ++i) {
			arr[i] = Long.parseLong(idArr[i]);
		}

		return createIdArrStr(arr, fieldName, needAnd);
	}

	public static String createMsgContent(BusinessBillItem item, List mtList) {
		String msgContent = EncCommonHelper.getSimpleObjectName(mtList,
				item.getMakeTypeId())
				+ " | "
				+ item.getFinishedContent()
				+ " | "
				+ item.getProName()
				+ " | " + item.getSpecification();
		if (!item.getPriceType().equals("AREA")
				&& !item.getPriceType().equals("LENGTH")) {
			msgContent = msgContent + " | " + item.getUnit() + " | "
					+ EncCommonHelper.parseBigDecimal(item.getAmount());
		} else {
			msgContent = msgContent + " x "
					+ EncCommonHelper.parseBigDecimal(item.getAmount());
			String unit;
			if (item.getPriceType().equals("AREA")) {
				unit = "平方米";
			} else if (item.getLengType().equals("M")) {
				unit = "米";
			} else {
				unit = "公分";
			}

			msgContent = msgContent + " | " + unit + " | "
					+ EncCommonHelper.parseBigDecimal(item.getSquareNum());
		}

		msgContent = msgContent + " | " + item.getMakeRequire();
		return msgContent;
	}

	public static void sendSms(String phone, String name, String content,
			String smsSign, BaseDao baseDao, IdGenerator idGenerator) {
		if (isMobileCode(phone) && getSmsBalance() > 0.0D) {
			content = createSmsContentWithSign(content, smsSign);
			SmsTask t = new SmsTask();
			t.setContent(content);
			t.setCreaterId(0L);
			t.setCreaterName("系统自动");
			t.setCreateTime(new Date());
			t.setId(idGenerator.getId(SmsTask.class.getName()));
			t.setPlanTime((Date) null);
			t.setReceiverCode(phone);
			t.setReceiverName(name);
			baseDao.save(t);
		}

	}

	public static String createSmsContentWithSign(String content, String sign) {
		String smsSignFormat = EncCommonHelper.getProperty("smsSignFormat");
		String smsSignPosition = EncCommonHelper.getProperty("smsSignPosition");
		return sign != null && !sign.equals("") ? (smsSignPosition != null
				&& smsSignPosition.equals("START") ? smsSignFormat.replace(
				"XXX", sign) + content : content
				+ smsSignFormat.replace("XXX", sign)) : content;
	}

	public static void sendProCompMsg(Map map, List mtList, UserBean ub,
			StafferDao stafferDao, IdGenerator idGenerator) {
		long billId = ((Long) map.get("billId")).longValue();
		long depId = ((Long) map.get("depId")).longValue();
		long mtId = ((Long) map.get("mtId")).longValue();
		long estId = ((Long) map.get("estId")).longValue();
		String billCode = (String) map.get("billCode");
		String currProName = (String) map.get("currProName");
		String msgContent = (String) map.get("msgContent");
		Establishment est = (Establishment) stafferDao.get(Establishment.class,
				estId);
		String mtName = EncCommonHelper.getSimpleObjectName(mtList, mtId);
		String msgTitle = est.getEstName() + billCode + mtName + "在"
				+ currProName + "已完工";
		List staList = stafferDao.getList(depId, true, false, "", "");
		sendMessage(msgTitle, msgContent, billId, ub, staList, stafferDao,
				idGenerator);
	}

	public static void sendFolCompMsg(Map map, UserBean ub, List saFolRecList,
			BaseDao baseDao, IdGenerator idGenerator) {
		long billId = ((Long) map.get("billId")).longValue();
		long estId = ((Long) map.get("estId")).longValue();
		String billCode = (String) map.get("billCode");
		Date deliDate = (Date) map.get("deliDate");
		String follIdStr = (String) map.get("follIdStr");
		String follNameStr = (String) map.get("follNameStr");
		String msgContent = (String) map.get("msgContent");
		Establishment est = (Establishment) baseDao.get(Establishment.class,
				estId);
		String msgTitle = est.getEstName() + billCode;
		if (deliDate != null) {
			SimpleDateFormat sendMap = new SimpleDateFormat("yyyy-MM-dd");
			msgTitle = msgTitle + "交货日期" + sendMap.format(deliDate);
		}

		msgTitle = msgTitle + "已完工";
		HashMap arg22 = new HashMap();
		if (follIdStr != null && !follIdStr.equals("")) {
			String it = follIdStr.substring(1);
			it = it.substring(0, it.length() - 1);
			String[] receList = it.split(";");
			String[] key = follNameStr.split(";");

			for (int objs = 0; objs < receList.length; ++objs) {
				if (receList[objs] != null && !receList[objs].equals("")) {
					String id = receList[objs].split(":")[0];
					String name = key[objs].split(" ")[0];
					if (!arg22.containsKey(id)) {
						arg22.put(id, name);
					}
				}
			}
		}

		String arg27;
		for (int arg23 = 0; arg23 < saFolRecList.size(); ++arg23) {
			Staffer arg25 = (Staffer) ((Object[]) saFolRecList.get(arg23))[1];
			arg27 = String.valueOf(arg25.getId());
			if (!arg22.containsKey(arg27)) {
				arg22.put(arg27, arg25.getStafferName());
			}
		}

		Iterator arg24 = arg22.keySet().iterator();
		ArrayList arg26 = new ArrayList();

		while (arg24.hasNext()) {
			arg27 = arg24.next().toString();
			Object[] arg28 = new Object[]{Long.valueOf(Long.parseLong(arg27)),
					(String) arg22.get(arg27)};
			arg26.add(arg28);
		}

		doSendMessage(msgTitle, msgContent, billId, ub, arg26, baseDao,
				idGenerator);
	}

	public static void sendBusCompSms(Map map, String customTxt,
			String entShortName, BaseDao baseDao, IdGenerator idGenerator) {
		Date ordeDate = (Date) map.get("ordeDate");
		String phone = (String) map.get("phone");
		String linkman = (String) map.get("linkman");
		String billCode = (String) map.get("billCode");
		String billCont = (String) map.get("content");
		SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
		String content = "您在" + sf.format(ordeDate) + "下的订单" + billCode + "（"
				+ billCont + "）已经完工，谢谢合作！" + customTxt;
		sendSms(phone, linkman, content, entShortName, baseDao, idGenerator);
	}

	public static void sendBusClieSms(Map map, String customTxt,
			String entShortName, BaseDao baseDao, IdGenerator idGenerator) {
		String phone = (String) map.get("phone");
		String linkman = (String) map.get("linkman");
		String billCode = (String) map.get("billCode");
		String billCont = (String) map.get("content");
		String content = billCont + "的业务单已下单成功，我司已安排车间制作，单号为：" + billCode + "。"
				+ customTxt;
		sendSms(phone, linkman, content, entShortName, baseDao, idGenerator);
	}

	public static void sendMessage(String msgTitle, String msgContent,
			long relationId, UserBean ub, List stafList, BaseDao baseDao,
			IdGenerator idGenerator) {
		ArrayList receList = new ArrayList();

		for (int j = 0; j < stafList.size(); ++j) {
			Object[] objs = new Object[2];
			Staffer sta = (Staffer) stafList.get(j);
			objs[0] = Long.valueOf(sta.getId());
			objs[1] = sta.getStafferName();
			receList.add(objs);
		}

		doSendMessage(msgTitle, msgContent, relationId, ub, receList, baseDao,
				idGenerator);
	}

	private static void doSendMessage(String msgTitle, String msgContent,
			long relationId, UserBean ub, List receList, BaseDao baseDao,
			IdGenerator idGenerator) {
		if (receList != null && receList.size() > 0) {
			String recName = "";

			for (int msgId = 0; msgId < receList.size(); ++msgId) {
				Object[] objs = (Object[]) receList.get(msgId);
				if ((recName + ";" + objs[1]).length() > 13) {
					recName = recName + "...";
					break;
				}

				if (!recName.equals("")) {
					recName = recName + ";";
				}

				recName = recName + objs[1];
			}

			long arg16 = idGenerator.getId(Message.class.getName());
			Message m = new Message();
			m.setContent(msgContent);
			m.setId(arg16);
			m.setReceiverName(recName);
			if (ub != null) {
				m.setSenderId(ub.getStaffer().getId());
				m.setSenderName(ub.getStaffer().getStafferName());
			} else {
				m.setSenderId(0L);
				m.setSenderName("系统");
			}

			m.setSenderDelete("Y");
			m.setTitle(msgTitle);
			m.setRelationId(relationId);
			baseDao.save(m);
			long curId = idGenerator.getId(MessageReceiver.class.getName(),
					receList.size());

			for (int i = 0; i < receList.size(); ++i) {
				Object[] objs1 = (Object[]) receList.get(i);
				MessageReceiver r = new MessageReceiver();
				r.setId(curId);
				r.setMessageId(arg16);
				r.setReceiverId(((Long) objs1[0]).longValue());
				r.setReceiverName((String) objs1[1]);
				baseDao.save(r);
				++curId;
			}
		}

	}

	public static List parseBaList(List baList, EnterpriseInfo ent,
			UserBean ub, long dfTsId, long specId) {
		ArrayList list = new ArrayList();

		for (int i = 0; i < baList.size(); ++i) {
			BankAccount ba = (BankAccount) baList.get(i);
			boolean isOk = false;
			if (specId != 0L && ba.getId() == specId) {
				isOk = true;
			} else if (ba.getEnabled().equals("Y")
					&& ba.getStatus().equals("Y")) {
				if (ent.getBankPr().equals("Y")) {
					if (ub.getUser().getUserType() == 1
							|| ub.getBaPrivs().indexOf(";" + ba.getId() + ";") != -1) {
						isOk = true;
					}
				} else if (ent.getBankTs().equals("Y")) {
					if (dfTsId != 0L) {
						if (ba.getTallySetId() == dfTsId) {
							isOk = true;
						}
					} else if (ub.getUser().getUserType() == 1
							|| ub.getTsPrivs().indexOf(
									";" + ba.getTallySetId() + ";") != -1) {
						isOk = true;
					}
				} else {
					isOk = true;
				}
			}

			if (isOk) {
				list.add(ba);
			}
		}

		return list;
	}

	public static UserStatus doUserLogin(String userName, String password,
			String mark, UserDao userDao, StafferDao stafferDao,
			UserPoDao userPoDao, UserPrivilegeDao userPrivilegeDao,
			WorkCenterDao workCenterDao, TallySetDao tallySetDao,
			IdGenerator idGenerator, HttpServletRequest request) {
		User u = userDao.get(userName);
		Staffer staffer = null;
		Department dep = null;
		if (u != null && u.getStafferId() != 0L) {
			staffer = (Staffer) stafferDao.get(Staffer.class, u.getStafferId());
			if (staffer != null && staffer.getDepartmentId() != 0L) {
				dep = (Department) stafferDao.get(Department.class,
						staffer.getDepartmentId());
			}
		}

		EnterpriseInfo en = EncCommonHelper.getEnterpriseInfo(request);
		UserStatus s = EncLoginFormCtrHelper.checkUser(u, password, staffer,
				dep, en, request);
		if (s.isNeedUpdate()) {
			userDao.update(u);
		}

		if (s.getAlertMsg().equals("")) {
			UserBean log = EncCommonHelper.getCurrentUserAccount(request);
			List tallySetList;
			if (u.getUserType() != 1) {
				tallySetList = userPrivilegeDao.getList(u.getId());
				List wcList = userPoDao.getList(u.getId());
				EncCommonHelper.setUserPrivilegeInfo(log, en, tallySetList,
						wcList);
			}

			tallySetList = getTallySetList(tallySetDao, log);
			log.setTallySets(tallySetList);
			if (tallySetList.size() == 1) {
				TallySet wcList2 = (TallySet) tallySetList.get(0);
				log.getUser().setDfTsId(wcList2.getId());
				log.setDfTsName(wcList2.getTitle());
				log.setNeedTsSelect("N");
			} else if (log.getUser().getDfTsId() != 0L) {
				String wcList1 = EncCommonHelper.getSimpleObjectName(
						tallySetList, log.getUser().getDfTsId());
				if (wcList1 != null && !wcList1.equals("")) {
					log.setDfTsName(wcList1);
				} else {
					log.getUser().setDfTsId(0L);
				}
			}

			Object wcList3;
			if (log.getUser().getUserType() != 1
					&& en.getWorkCenter().equals("Y")) {
				wcList3 = workCenterDao.getList(log.getUser().getId());
			} else {
				wcList3 = new ArrayList();
			}

			log.setWorkCenters((List) wcList3);
			SystemLog log1 = new SystemLog();
			log1.setId(idGenerator.getId(SystemLog.class.getName()));
			log1.setActionCode("LOGIN");
			log1.setLogType("USER_LOG");
			log1.setCreaterId(log.getStaffer().getId());
			log1.setCreaterName(log.getStaffer().getStafferName());
			log1.setDepName(log.getDepName());
			log1.setDepId(log.getStaffer().getDepartmentId());
			log1.setMark(mark);
			log1.setStatus("S");
			log1.setUserName(log.getUser().getUserName());
			log1.setIp(request.getRemoteAddr());
			userDao.save(log1);
		} else {
			SystemLog log2 = new SystemLog();
			log2.setId(idGenerator.getId(SystemLog.class.getName()));
			log2.setActionCode("LOGIN");
			log2.setLogType("USER_LOG");
			log2.setCreaterId(0L);
			log2.setMark(mark);
			log2.setStatus("F");
			log2.setUserName(userName);
			log2.setIp(request.getRemoteAddr());
			userDao.save(log2);
		}

		return s;
	}

	public static void doUserLogout(BaseDao baseDao, IdGenerator idGenerator,
			HttpServletRequest request, String type) {
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		String ip = request.getRemoteAddr();
		doUserLogout(baseDao, idGenerator, ub, ip, type);
		EncCommonHelper.setCurrentUserAccount(request, (UserBean) null);
	}

	public static void doUserLogout(BaseDao baseDao, IdGenerator idGenerator,
			UserBean ub, String ip, String type) {
		if (ub != null) {
			SystemLog log = new SystemLog();
			log.setId(idGenerator.getId(SystemLog.class.getName()));
			log.setActionCode("LOGOUT");
			log.setLogType("USER_LOG");
			log.setCreaterId(ub.getStaffer().getId());
			log.setCreaterName(ub.getStaffer().getStafferName());
			log.setDepName(ub.getDepName());
			log.setDepId(ub.getStaffer().getDepartmentId());
			log.setMark(type);
			log.setStatus("S");
			log.setUserName(ub.getUser().getUserName());
			log.setIp(ip);
			baseDao.save(log);
			if (type != null && type.equals("APP")) {
				OnlineListener.removeAppUser(ub.toString());
			} else {
				OnlineListener.removeUser(ub.toString());
			}
		}

	}

	public static String getCellVal(HSSFCell cell, int maxLen) {
		String str;
		if (cell == null) {
			str = "";
		} else if (cell.getCellType() != 0 && cell.getCellType() != 2) {
			str = cell.getRichStringCellValue().getString();
		} else if (HSSFDateUtil.isCellDateFormatted(cell)) {
			SimpleDateFormat e = new SimpleDateFormat("yyyy-MM-dd");
			str = e.format(cell.getDateCellValue());
		} else {
			try {
				str = (new BigDecimal(cell.getNumericCellValue())).setScale(4,
						4).toPlainString();
				if (str != null && !str.equals("")) {
					String[] e1 = str.split("\\.");
					if (e1.length > 1) {
						while (e1[1].endsWith("0")) {
							e1[1] = e1[1].substring(0, e1[1].length() - 1);
						}

						if (e1[1].equals("")) {
							str = e1[0];
						} else {
							str = e1[0] + "." + e1[1];
						}
					}
				}
			} catch (Exception arg3) {
				str = cell.getRichStringCellValue().getString();
			}
		}

		if (str == null) {
			str = "";
		}

		str = str.trim();
		if (maxLen != 0 && str.length() > maxLen) {
			str = str.substring(0, maxLen);
		}

		return str;
	}

	public static String appendAlertMsg(String alertMsg, String appendStr) {
		if (alertMsg != null && !alertMsg.equals("")) {
			alertMsg = alertMsg + "<br>";
		}

		alertMsg = alertMsg + appendStr;
		return alertMsg;
	}

	public static boolean isEmpty(String str) {
		return str == null || str.trim().equals("");
	}

	public static List parseStorList(List list, long tsId, long dfId) {
		ArrayList arr = new ArrayList();

		for (int i = 0; i < list.size(); ++i) {
			Storehouse obj = (Storehouse) list.get(i);
			if (obj.getId() == dfId || obj.getTallySetId() == tsId
					&& obj.getEnabled().equals("Y")) {
				arr.add(obj);
			}
		}

		return arr;
	}

	public static String parseNull(String str) {
		return str == null ? "" : str;
	}

	public static List createTreeArray(List list, String childPrevStr,
			boolean justEnabled) {
		ArrayList arr = new ArrayList();
		Stack stack = new Stack();
		Stack layerNumStack = new Stack();

		TreeObjectInterface obj;
		for (int nextParentCode = list.size(); nextParentCode > 0; --nextParentCode) {
			obj = (TreeObjectInterface) list.get(nextParentCode - 1);
			boolean currentLayerNum = false;
			if (justEnabled) {
				if (obj.getEnabled().equals("Y")) {
					currentLayerNum = true;
				}
			} else {
				currentLayerNum = true;
			}

			if (currentLayerNum
					&& (obj.getObjectParentCode() == null
							|| obj.getObjectParentCode().equals("") || obj
							.getObjectParentCode().equals("0"))) {
				stack.push(obj);
				layerNumStack.push("1");
			}
		}

		while (!stack.isEmpty()) {
			obj = (TreeObjectInterface) stack.pop();
			int arg13 = Integer.parseInt(((String) layerNumStack.pop())
					.toString());
			String tmpStr = "";

			int i;
			for (i = 0; i < arg13 - 1; ++i) {
				tmpStr = tmpStr + childPrevStr;
			}

			arr.add(new String[]{obj.getObjectCode(),
					tmpStr + obj.getObjectName()});
			String arg12 = obj.getObjectCode();

			for (i = list.size(); i > 0; --i) {
				TreeObjectInterface tmpObj = (TreeObjectInterface) list
						.get(i - 1);
				boolean itemOk = false;
				if (justEnabled) {
					if (obj.getEnabled().equals("Y")) {
						itemOk = true;
					}
				} else {
					itemOk = true;
				}

				if (itemOk && tmpObj.getObjectParentCode().equals(arg12)) {
					stack.push(tmpObj);
					layerNumStack.push(String.valueOf(arg13 + 1));
				}
			}
		}

		return arr;
	}
}